package com.mjkj.demo.utils;
/*
 ** @Author:      Geraint
 ** @CreateDate:  2023-12-04  15:47
 ** @ProjectName: TeaExpoPark
 ** @Package:     com.mjkj.demo.utils
 ** @Edit :       geraint
 ** @EditDate:    2023-12-04  15:47
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

public class PingUtils {
    public static boolean isHostReachable(String ipAddress) {
        if (!IPAddressUtils.isValidIPAddress(ipAddress)) {
            return false;
        }
        try {
            Process process = new ProcessBuilder("ping", ipAddress).start();

            // 读取命令输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                // 判断输出中是否包含"ip地址"和"ttl"，表示主机是可达的
                if (line.contains(ipAddress) && line.toLowerCase().contains("ttl")) {
                    return true;
                } else if (line.contains("timeout")) {
                    return false;
                }
            }

            // 等待命令执行完成，最长等待1秒
            if (!process.waitFor(1, TimeUnit.SECONDS)) {
                process.destroy(); // 超时后终止进程
                return false;
            }

            // 检查命令执行结果
            int exitCode = process.exitValue();
            if (exitCode != 0) {
                return false;
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        return false;
    }
}
